package main

import (
	"cs-backend/controller"
	"cs-backend/db"
	"cs-backend/dto"
	"cs-backend/middleware"
	"cs-backend/util"
	"github.com/go-playground/validator/v10"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/core/router"
	"time"
)

func main() {

	time.LoadLocation("Asia/Shanghai")

	app := newApp()
	util.Log = app.Logger()
	app.Run(iris.Addr(":8080"))
}

func newApp() (app *iris.Application) {
	app = iris.Default()
	// 启用验证器
	app.Validator = validator.New()
	//app.Use(logger.New())
	//将“before”处理程序注册为将要执行的第一个处理程序
	//在所有域的路由上。
	//或使用`UseGlobal`注册一个将跨子域触发的中间件。
	//app.Use(middleware.Before)

	//将“after”处理程序注册为将要执行的最后一个处理程序
	//在所有域的路由'处理程序之后。
	//app.Done(middleware.After)

	app.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) {
		_, _ = ctx.JSON(dto.ResponseNotFound())
	})
	app.OnErrorCode(iris.StatusInternalServerError, func(ctx iris.Context) {
		_, _ = ctx.JSON(dto.ResponseInternalServerError())
	})

	// 跨域访问
	crs := util.Cors()

	iris.RegisterOnInterrupt(func() {
		db.CloseEngine()
	})

	// Jwt middleware
	j := util.Jwt()

	app.Post("/", controller.GetTokenHandler)
	app.Get("/hello", controller.Hello)

	v1 := app.Party("/v1", crs).AllowMethods(iris.MethodOptions)
	{
		v1.Use(j.Serve, middleware.Before)
		v1.Done(middleware.After)

		v1.Get("/secured", controller.CheckAuthenticatedHandler)

		v1.PartyFunc("/user", func(userParty router.Party) {
			userCtrl := new(controller.UserController)
			userParty.Get("/{id:int64}", userCtrl.GetById)
			userParty.Post("", userCtrl.Insert)
			userParty.Put("", userCtrl.Update)
			userParty.Delete("/{id:int64}", userCtrl.DeleteById)
			userParty.Get("/all", userCtrl.ListAll)
			userParty.Get("/page", userCtrl.ListPage)
			userParty.Get("/query", userCtrl.SqlMapQuery)
		})
		//v1.PartyFunc("/role", func(roleParty router.Party) {
		//	roleParty.Get("/{id:int64}", controller.GetRoleById)
		//	roleParty.Post("", controller.InsertRole)
		//	roleParty.Put("", controller.UpdateRole)
		//	roleParty.Delete("/{id:int64}", controller.DeleteRoleById)
		//	roleParty.Get("/all", controller.ListAllRole)
		//	roleParty.Get("/page", controller.ListPageRole)
		//	roleParty.Get("/query", controller.SqlMapQueryRole)
		//
		//})
		v1.PartyFunc("/news", func(newsParty router.Party) {
			newsParty.Get("/{id:int64}", controller.GetNewsById)
			newsParty.Post("/", controller.InsertNews)
			newsParty.Put("/", controller.UpdateNews)
			newsParty.Delete("/{id:int64}", controller.DeleteNewsById)
			newsParty.Get("/all", controller.ListAllNews)
			newsParty.Get("/page", controller.ListPageNews)
		})

	}
	return app
}
